<template>
<div>
    <!--<div class="panel">
        <div class="hd">出发地选择</div>
        <div class="bd">
            <el-form>
                <el-form-item label="出发地：" style="margin-bottom: 0;">
                    <el-radio-group v-model="active.region" @change="regionChange">
                        <el-radio :label="item.id" v-for="item in data.departureList" :key="item.id">{{item.areaName}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </div>
    </div>-->
    <div class="panel">
        <div class="hd">日期选择</div>
        <div class="bd">
            <div class="calendar">
                <div class="action">
                    <el-button @click="prev" class="bl" type="text" icon="el-icon-arrow-left">往前3个月</el-button>
                    <el-button @click="next" class="br" type="text">往后3个月<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                </div>
                <div class="box" v-for="(item, idx) in calendar.data" :key="idx">
                    <div class="tit">
                        <el-checkbox v-model="item.checked" @change="changeStatusMonth(idx)">{{item.month}}</el-checkbox>
                    </div>
                    <div class="cont">
                        <div class="week">
                            <div class="it it-red">
                                <el-checkbox v-model="item.weekChecked[7]" @change="changeStatusCol(idx,7)">日</el-checkbox>
                            </div>
                            <div class="it">
                                <el-checkbox v-model="item.weekChecked[1]" @change="changeStatusCol(idx,1)">一</el-checkbox>
                            </div>
                            <div class="it">
                                <el-checkbox v-model="item.weekChecked[2]" @change="changeStatusCol(idx,2)">二</el-checkbox>
                            </div>
                            <div class="it">
                                <el-checkbox v-model="item.weekChecked[3]" @change="changeStatusCol(idx,3)">三</el-checkbox>
                            </div>
                            <div class="it">
                                <el-checkbox v-model="item.weekChecked[4]" @change="changeStatusCol(idx,4)">四</el-checkbox>
                            </div>
                            <div class="it">
                                <el-checkbox v-model="item.weekChecked[5]" @change="changeStatusCol(idx,5)">五</el-checkbox>
                            </div>
                            <div class="it it-red">
                                <el-checkbox v-model="item.weekChecked[6]" @change="changeStatusCol(idx,6)">六</el-checkbox>
                            </div>
                        </div>
                        <div class="days">
                            <div class="it" v-for="(n,i) in item.startSpace" :key="i">&nbsp;</div>
                            <div class="it" v-for="(it, i) in item.days" :key="i" @click="changeStatus(it.checked,idx,i)">
                                <div :class="it.checked ? 'bk_blue' :''">
                                    <div class="r">{{it.name}}</div>
                                    <div v-if="it.price" class="r price">￥{{it.price}}</div>
                                    <div v-if="it.stock && it.stock !== -1" class="r surplus">余：{{it.stock}}</div>
                                </div>
                            </div>
                            <div class="it" v-for="(n,i) in item.endSpace" :key="i">&nbsp;</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="showPriceModal">设置价格</el-button>
    </div>

    <el-dialog title="售价设置" :visible.sync="dialog.visible" width="960px">
        <div slot="title"></div>
        <div>
            <div class="panel">
                <div class="hd">售价设置</div>
                <div class="bd">
                    <table cellspacing="0">
                        <tr>
                            <th>资源</th>
                            <th>零售价</th>
                            <!--<th>市场价</th>-->
                            <!--<th>优惠价</th> -->
                        </tr>
                        <!-- <tr v-for="(item,i) in datePrice.price" :key="i">
                            <td v-if="!noCrowd">{{{'adult':'成人','child':'儿童','baby':'婴儿','old':'老人','single_room':'单房差设置'}[item.type]}}</td>
                            <td v-else>人均</td>
                            <td>
                                <el-input v-model.number="item.sprice" size="small" style="width: 140px;" placeholder=""></el-input>
                            </td>
                            <td>
                                <el-input v-model.number="item.rprice" size="small" style="width: 140px;" placeholder=""></el-input>
                            </td>
                            <td>
                                <el-input v-model.number="item.dprice" size="small" style="width: 140px;" placeholder=""></el-input>
                            </td>
                        </tr> -->
                        <tr v-for="(item,i) in datePrice.price" :key="i">
                            <td>
                                <span v-if="!noCrowd" class="mr10">{{{'adult':'成人','child':'儿童','baby':'婴儿','old':'老人','single_room':'单房差设置'}[item.type]}}</span>
                                <span v-else class="mr10">人均</span>
                                <el-input v-if="item.type!='single_room'" v-model.number="item.quantity" size="small" style="width: 140px;" @input="getAmount()" placeholder=""></el-input>
                                <span v-if="item.type!='single_room'" class="ml10">人</span>
                            </td>
                            <td>
                                <el-input v-model.number="item.rprice" size="small" style="width: 140px;" @input="getAmount()" placeholder=""></el-input>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div class="panel">
                <div class="hd">共计金额</div>
                <div class="bd">零售价: ¥{{datePrice.amount}}</div>
            </div>
            <!--<div class="panel">
                <div class="hd">库存设置</div>
                <div class="bd">
                    <el-form>
                        <el-form-item label="库存：">
                            <el-radio-group v-model="datePrice.isStock">
                                <el-radio :label="false">不用库存</el-radio>
                                <el-radio :label="true">固定库存</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="库存数量：" v-if="datePrice.isStock">
                            <el-input-number size="small" v-model="datePrice.stock" :min="0"></el-input-number>
                        </el-form-item>
                    </el-form>
                </div>
            </div>-->
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="setPrice">确 定</el-button>
        </span>
    </el-dialog>

</div>
</template>

<script>
export default {
  props: ['prodId', 'data', 'crowdInfo'],
  data () {
    return {
      loading: false,
      noCrowd: false,
      active: {
        region: '',
        date: ['']
      },
      dialog: {
        visible: false,
        form: {
          stock: 1,
          isStock: true

        }
      },
      datePrice: {
        price: []
      },
      calendar: {
        cur: 0,
        vals: [],
        data: [{}, {}, {}]
      },
      v: null,
      selectIds: [],
      dataForm: {
        customizationId: '',
        priceList: []
      }
    }
  },
  watch: {},
  created () {
    this.dataForm.customizationId = this.prodId
    if (this.data.departureList && this.data.departureList.length > 0) {
      this.active.region = this.data.departureList[0].id
      this.initData()
    } else {
      this.buildData()
    }
    let noCrowdFlag = false
    noCrowdFlag = !this.data.crowdList || this.data.crowdList.length == 0
    if (!noCrowdFlag) {
      if (this.data.crowdList.length == 1 && this.data.crowdList[0].type == 'all') {
        noCrowdFlag = true
      }
    }
    this.noCrowd = noCrowdFlag
  },
  methods: {
    // 获取总额
    getAmount () {
      // 获取总额
      let amount = 0
      let singlePrice = 0
      this.datePrice.price.map(value => {
        amount = amount + Number(value.quantity) * Number(value.rprice)
        if (value.type == 'single_room') {
          singlePrice = value.rprice
        }
      })
      if (singlePrice) {
        amount += singlePrice
      }
      this.datePrice.amount = amount
    },
    regionChange (v) {
      console.log(v)
      this.active.region = v
      this.initData()
    },
    initData () {
      const _datePrice = {
        price: []
      }
      // 重新获取crowdList
      this.$http.get('/customization/' + this.prodId).then(res => {
        const dataInfo = res.data.data
        let noCrowdFlag = false
        noCrowdFlag = !dataInfo.crowdList || dataInfo.crowdList.length == 0
        if (!noCrowdFlag) {
          if (dataInfo.crowdList.length == 1 && dataInfo.crowdList[0].type == 'all') {
            noCrowdFlag = true
          }
        }
        this.noCrowd = noCrowdFlag
        this.data = dataInfo
        if (this.data.crowdList.length > 0) {
          _datePrice.stock = this.data.crowdList[0].stock
          _datePrice.isStock = true
          _datePrice.amount = 0
          this.data.crowdList.map((item) => {
            _datePrice.price.push({
              id: item.id,
              type: item.type,
              sprice: 0,
              rprice: 0,
              quantity: 0
              // dprice: 0,
            })
          })
          if (!this.noCrowd) {
            _datePrice.price.push({
              id: 0,
              type: 'single_room',
              sprice: 0,
              rprice: 0,
              quantity: null
            })
          }
          this.datePrice = _datePrice
        }
        this.active.date = []
        this.data.priceList.map(item => {
          if (item.departureId === this.active.region) {
            this.active.date = item.datePriceList
          }
        })
        this.buildData()
      })
      // if (this.data.crowdList.length > 0) {
      //     _datePrice.stock = this.data.crowdList[0].stock;
      //     _datePrice.isStock = true;
      //     this.data.crowdList.map((item) => {
      //         _datePrice.price.push({
      //             id: item.id,
      //             type: item.type,
      //             sprice: 0,
      //             rprice: 0,
      //             dprice: 0,
      //         })
      //     })
      //     this.datePrice = _datePrice;
      // }
      // this.active.date = [];
      // this.data.priceList.map(item => {
      //     if (item.departureId === this.active.region) {
      //         this.active.date = item.datePriceList;
      //     }
      // });
      // this.buildData();
    },
    // 设置单个日期的价格/库存
    changeStatus (value, index0, index1) {
      this.calendar.data[index0].days[index1].checked = !value
    },
    showPriceModal () {
      this.dialog.visible = true
    },

    changeStatusCol (index, week) {
      const data = JSON.parse(JSON.stringify(this.calendar.data[index]))
      data.days = data.days.map(day => {
        if (day.week === week) {
          day.checked = data.weekChecked[week]
        }
        return day
      })
      this.$set(this.calendar.data, index, data)
    },

    changeStatusMonth (index) {
      const data = JSON.parse(JSON.stringify(this.calendar.data[index]))
      data.days = data.days.map(day => {
        day.checked = data.checked
        return day
      })
      this.$set(this.calendar.data, index, data)
    },

    formatDate (index0, index1) {
      let day_num = index1 + 1
      day_num = day_num + ''
      day_num = day_num.padStart(2, '0')
      const year_num = this.calendar.data[index0].month.split('年')[0]
      let month_num = this.calendar.data[index0].month.split('年')[1]
      month_num = month_num.split('月')[0] + ''
      month_num = month_num.padStart(2, '0')
      const date = year_num + '-' + month_num + '-' + day_num + ' 00:00:00'
      return date
    },
    // 设置价格
    setPrice () {
      const isValid = this.validatePrice()
      if (!isValid) {
        return this.$message.error('市场价必须高于结算价和优惠价,优惠价必须高于结算价！')
      }
      const price = this.datePrice
      const data = JSON.parse(JSON.stringify(this.calendar.data))
      data.forEach(days => {
        days.days.map(day => {
          if (day.checked) {
            day.priceData = price
            day.checked = false
            day.price = price.price[0].rprice
            day.stock = price.stock
          }
        })
      })
      console.log('setPricedata', data)
      this.calendar.data = data
      this.dialog.visible = false
      this.submit()
    },

    // 验证，市场价必须高于结算价
    validatePrice () {
      const flag = this.datePrice.price.some(item => {
        console.log('item=====', item)
        if (item.type != 'single_room') {
          if (item.rprice >= item.sprice) {
            return true
          }
          // if (item.dprice && item.dprice < item.sprice) {
          //     return true
          // }
          // if (item.dprice && item.rprice < item.dprice) {
          //     return true
          // }
        }
      })
      return flag
    },

    submit () {
      this.loading = true
      const data = {
        customizationId: this.prodId,
        priceList: []
      }
      const _data = JSON.parse(JSON.stringify(this.calendar.data))
      _data.forEach(days => {
        days.days.map(day => {
          if (day.price) {
            const {
              priceData
            } = day
            console.log('priceData=====', priceData)
            if (priceData.price && priceData.price.length > 0) {
              priceData.price.forEach(item => {
                console.log('item=====', {
                  date: day.value,
                  departureId: this.active.region,
                  type: item.type,
                  customizationCrowdId: item.id,
                  settlementPrice: item.sprice, // 优惠价
                  retailPrice: item.rprice, // 零售价
                  // stock: priceData.stock,
                  // discountPrice: item.dprice, // 优惠价
                  customizationId: this.prodId,
                  isStock: priceData.isStock
                })
                // 如果单房差价格为0，则不传
                const noSinglePrice = item.type != 'single_room'
                const singlePrice = item.type == 'single_room' && item.rprice
                if (noSinglePrice || singlePrice) {
                  data.priceList.push({
                    date: day.value,
                    departureId: this.active.region,
                    type: item.type,
                    customizationCrowdId: item.id,
                    settlementPrice: item.sprice, // 优惠价
                    retailPrice: item.rprice, // 零售价
                    // stock: priceData.stock || item.stock,
                    // discountPrice: item.dprice, // 优惠价
                    customizationId: this.prodId,
                    isStock: priceData.isStock,
                    quantity: item.quantity
                  })
                }
              })
            }
          }
        })
      })
      this.$http.put('/customization/price', data).then(res => {
        console.log('======', res)
        const {
          code,
          msg,
          data
        } = res.data
        if (code !== 0) {
          this.$message({
            message: msg,
            type: 'error'
          })
        } else {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.$parent.getInfo()
        }

        this.loading = false
      })
    },

    buildData () {
      const m = this.calendar.cur
      console.log(m)
      // 获取房前日期
      this.$set(this.calendar.data, 0, this.getDays(m))
      this.$set(this.calendar.data, 1, this.getDays(m + 1))
      this.$set(this.calendar.data, 2, this.getDays(m + 2))
    },
    prev () {
      this.calendar.cur -= 3
      this.buildData()
    },
    next () {
      this.calendar.cur += 3
      this.buildData()
    },
    getDays (offset) {
      // 偏移月
      const t = new Date()
      let y = t.getFullYear()
      let m = t.getMonth() + 1 + offset
      let d = null
      t.setMonth(m - 1)
      t.setDate(1)
      d = t.getDay() // 1号星期几
      t.setMonth(m)
      t.setDate(0)
      const ds = t.getDate() // 当月天数
      const days = []
      const priceList = this.data.priceList // 价格数据 --- 显示
      let flag = false
      if (m > 12) {
        y += parseInt(m / 12)
        m = m % 12 == 0 ? 12 : m % 12
      } else if (m < 1) {
        y -= Math.ceil((Math.abs(m) + 1) / 12)
        m = m % 12 == 0 ? 12 : 12 + m % 12
      }
      for (let i = 1; i <= ds; i++) {
        const _date = y + '-' + m.toString().padStart(2, '0') + '-' + i.toString().padStart(2, '0') + ' 00:00:00'
        var result = this.active.date.some(item => {
          if (item.date + ' 00:00:00' === _date) {
            const _item = item.crowdPriceList
            if (_item.length > 0) {
              flag = priceList.some(value => { return value.date == _date })
              let price = []
              if (flag) {
                price = _item.map(item => {
                  return {
                    id: item.customizationCrowdId,
                    type: item.type,
                    sprice: item.settlementPrice,
                    rprice: item.retailPrice,
                    dprice: item.discountPrice,
                    stock: item.stock,
                    quantity: item.quantity
                  }
                })
              } else {
                price = _item.map(item => {
                  return {
                    id: item.customizationCrowdId,
                    type: item.type,
                    sprice: item.settlementPrice,
                    rprice: item.retailPrice,
                    dprice: item.discountPrice,
                    stock: item.stock,
                    quantity: item.quantity
                  }
                })
              }

              days.push({
                name: i,
                value: _date,
                price: _item[0].retailPrice,
                stock: _item[0].stock,
                checked: false,
                priceData: {
                  price
                },
                week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
              })
              return true
            }
          }
        })
        if (!result) {
          if (priceList && priceList.length > 0) {
            flag = priceList.some(value => { return value.date == _date })
            if (flag) {
              const [datePrice] = priceList.filter(value => { return value.date == _date })
              days.push({
                name: i,
                value: _date,
                price: datePrice.retailPrice,
                stock: -1,
                priceItem: {},
                checked: false,
                priceData: {},
                week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
              })
            } else {
              days.push({
                name: i,
                value: _date,
                price: 0,
                stock: -1,
                priceItem: {},
                checked: false,
                priceData: {},
                week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
              })
            }
          } else {
            days.push({
              name: i,
              value: _date,
              price: 0,
              stock: -1,
              priceItem: {},
              checked: false,
              priceData: {},
              week: (d + i - 1) % 7 ? (d + i - 1) % 7 : 7
            })
          }
        }
      }

      return {
        month: y + '年' + m + '月',
        startSpace: d,
        endSpace: 42 - (d + ds),
        checked: false,
        days: days,
        weekChecked: [false, false, false, false, false, false, false]
      }
    },
    setNav (idx) {
      this.active = idx
    }
  }
}
</script>

<style lang="scss" scoped>
.mydialog {
    .el-dialog__body {
        padding: 0 !important;
    }

    .el-dialog__header {
        display: none !important;
    }
}
    .ml10 {

        margin-left: 10px;
    }
    .mr10 {
        margin-right: 10px;
    }
table {
    width: 800px;
    border-left: 1px solid #e7e8eb;
    border-top: 1px solid #e7e8eb;

    tr {
        th {
            background: #e9f5f9;
        }

        td,
        th {
            text-align: left;
            padding: 4px 6px;
            min-width: 160px;
            border-right: 1px solid #e7e8eb;
            border-bottom: 1px solid #e7e8eb;
        }
    }
}

.calendar {
    display: flex;
    position: relative;

    .action {
        position: absolute;
        top: 0;
        width: 100%;

        .bl {
            float: left;
        }

        .br {
            float: right;
        }
    }

    .bk_blue {
        height: 100%;
        color: #fff;
        background-color: #407ae6;
    }

    .box {
        flex: 1;
        margin-right: 10px;

        &:last-child {
            margin-right: 0;
        }

        .tit {
            text-align: center;
            height: 42px;
            line-height: 42px;
        }

        .cont {
            font-size: 12px;

            .week {
                display: flex;
                border-top: 1px solid #e7e8eb;
                border-left: 1px solid #e7e8eb;

                .it {
                    width: 14.28%;
                    padding: 4px 0;
                    background: #eff0f3;
                    border-right: 1px solid #e7e8eb;
                    text-align: center;

                    &.it-red /deep/ .el-checkbox__label {
                        color: #fe2724;
                    }
                }
            }

            .days {
                display: flex;
                flex-wrap: wrap;
                border-top: 1px solid #e7e8eb;
                border-left: 1px solid #e7e8eb;

                .it {
                    cursor: pointer;
                    width: 14.28%;
                    border-right: 1px solid #e7e8eb;
                    border-bottom: 1px solid #e7e8eb;
                    text-align: center;
                    height: 66px;
                    display: flex;
                    flex-direction: column;

                    /*padding: 6px 0;*/
                    .r {
                        flex: 1;
                    }

                    &.active {
                        background: #3753c6;
                        color: #fff;
                    }

                    &:nth-of-type(7n + 7) {
                        color: #fe2724;
                    }

                    &:nth-of-type(7n + 1) {
                        color: #fe2724;
                    }

                    .surplus,
                    .price {
                        color: #000;
                    }
                }
            }
        }
    }
}
</style>
